package com.sh.suhe.utildemos.utils.socket;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.net.InetSocketAddress;

public class SocketUtil {
    public static boolean isNetWorkConnected(Context context) {
        if (context == null) {
            return false;
        }

        try {
            ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager != null) {
                NetworkInfo info = manager.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    /**
     * 把形如192.168.1.1:8080的地址字符串转换成socket address
     * @param ip
     * @return
     */
    public static InetSocketAddress ipToSocketAdress(String ip) {
        final String[] strs = ip.split(":");
        if (strs.length >= 2) {
            try {
                int port = Integer.parseInt(strs[1]);
                return new InetSocketAddress(strs[0], port);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
